package com.powernode.ssm.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class LogConfigInitializer implements ApplicationRunner {

    private static final Logger log = LoggerFactory.getLogger(LogConfigInitializer.class);

    // 从 application.yml 中读取配置项 myapp.log.dir
    @Value("${myapp.log.dir:./log}") // 默认值为 ./log
    private String logDirPath;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 将日志目录路径设置到 JVM 系统属性中，key 为 myapp.log.dir
        System.setProperty("myapp.log.dir", logDirPath);

        log.info("📂 已设置日志目录系统属性：myapp.log.dir = {}", logDirPath);

        // 可选：同时创建日志目录（推荐）
        try {
            java.nio.file.Path path = java.nio.file.Paths.get(logDirPath);
            if (!java.nio.file.Files.exists(path)) {
                java.nio.file.Files.createDirectories(path);
                log.info("✅ 日志目录已自动创建: {}", path.toAbsolutePath());
            } else {
                log.debug("📂 日志目录已存在: {}", path.toAbsolutePath());
            }
        } catch (Exception e) {
            log.warn("⚠️ 无法创建日志目录 {}: {}", logDirPath, e.getMessage());
        }
    }
}
